package com.lianmai.chaincard.view;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;

import com.lianmai.chaincard.R;
import com.lianmai.chaincard.utils.FileUtil;
import com.lianmai.chaincard.utils.SDCardStore;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.youth.xframe.widget.XToast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 创建日期：2018/8/17 0017
 * 作者:Kite
 * 联系客服
 */
public class ContactServiceActivity extends BaseActivity {

    @BindView(R.id.img_wx_icon)
    ImageView imgWxIcon;

    private String filePath;

    private SDCardStore mSDCardStore;

    @Override
    public int getLayoutId() {
        return R.layout.activity_contact_service;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
    }

    @Override
    public void initView() {
        super.initView();
        setTitle(R.string.contact_service);
        imgWxIcon.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showDialog();
                return false;
            }
        });
    }

    private void showDialog() {
        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.dialog_fragment_qr_code)
                .setScreenWidthAspect(this, 0.96f)
                .setGravity(Gravity.BOTTOM)
                .setDialogAnimationRes(R.style.dialog_fragment_bottom_anim)
                .addOnClickListener(R.id.tv_save_phone, R.id.tv_cancel)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, android.view.View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.tv_save_phone:
                                savePath(getViewBitmap(imgWxIcon));
                                tDialog.dismiss();
                                break;
                            case R.id.tv_cancel:
                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();
    }

    private void savePath(Bitmap drawingCache) {
        mSDCardStore = new SDCardStore();
        filePath = mSDCardStore.getCameraDirPath() + "/pic_wx_code.png";
        if (FileUtil.isExist(filePath)) {
            XToast.error("已经保存到相册!");
            return;
        }

        Observable.create(new SaveObservable(drawingCache))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SaveSubscriber());
    }

    private class SaveObservable implements Observable.OnSubscribe<String> {

        private Bitmap drawingCache;

        SaveObservable(Bitmap drawingCache) {
            this.drawingCache = drawingCache;
        }

        @Override
        public void call(Subscriber<? super String> subscriber) {
            if (drawingCache == null) {
                subscriber.onError(new NullPointerException("保存失败"));
            } else {
                try {
                    FileOutputStream outStream = new FileOutputStream(new File(filePath));
                    drawingCache.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                    subscriber.onNext(Environment.getExternalStorageDirectory().getPath());
                    subscriber.onCompleted();
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    subscriber.onError(e);
                }
            }
        }
    }

    private class SaveSubscriber extends Subscriber<String> {

        @Override
        public void onCompleted() {
            XToast.success("保存成功!");
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            intent.setData(Uri.fromFile(new File(filePath)));
            sendBroadcast(intent);
        }

        @Override
        public void onError(Throwable e) {
            XToast.error("保存失败!");
        }

        @Override
        public void onNext(String s) {
        }
    }

    /**
     * 某些机型直接获取会为null，防止崩溃
     */
    private Bitmap getViewBitmap(android.view.View view) {
        if (view == null) {
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }

}
